package cha.app;

import java.util.ArrayList;
import java.util.TreeMap;

import android.util.Log;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class CustomSensorManager implements SensorEventListener {
  private static final String TAG = "CustomSensorManager";
  
  private SensorManager sm;
  private static TreeMap<String, Boolean> tm_activated;
  private TreeMap<String, Sensor> tm_sensor_map;
  private ArrayList<Sensor> all_sensors;
  private Object callback;
  
  CustomSensorManager(Context parent){
    Log.d( TAG, "Starting" );
    sm = (SensorManager)parent.getSystemService(Context.SENSOR_SERVICE);
    all_sensors = new ArrayList<Sensor>();
    tm_activated = new TreeMap<String, Boolean>();
    tm_sensor_map = new TreeMap<String, Sensor>();
    
    for(Sensor s : sm.getSensorList( Sensor.TYPE_ALL )){
      all_sensors.add( s );
      tm_activated.put( s.getName(), false );
      tm_sensor_map.put( s.getName(), s );
    }
  }
  
  public boolean register(String name){
    return register(tm_sensor_map.get( name ));
  }
  
  public boolean register(Sensor s){
    Log.d( TAG, "Registering: " + s.getName() + " - " + s.toString());
    tm_activated.put(s.getName(), true);
    return sm.registerListener( this, s, SensorManager.SENSOR_DELAY_NORMAL);
  }
  
  public void unregister(String name){
    unregister(tm_sensor_map.get(name));
  }
  
  public void unregister(Sensor s){
    tm_activated.put( s.getName(), false );
    sm.unregisterListener( this, s );
    Log.d( TAG, "Unregistering: " + s.getName() + " - " + s.toString());
  }
  
  public void onAccuracyChanged( Sensor sensor, int accuracy ) {
    // TODO Auto-generated method stub
  }

  public void onSensorChanged( SensorEvent event ) {
    String data = "";
    for(float val : event.values)
      data += (val + ", ");
    Log.d(TAG, event.sensor.getName() + " -- " + data);
  }
  
  public ArrayList<Sensor> getSensorList(){
    return all_sensors;
  }
  
  public boolean isActivated(String name){
    return isActivated(tm_sensor_map.get( name ));
  }
  
  public boolean isActivated(Sensor s){
    return tm_activated.get( s.getName() );
  }
}
